import Vue from 'vue';
import VueRouter from 'vue-router';
// import store from '@/store';
import order from './order';
import baseConfig from './base-config';
import course from './course';

Vue.use(VueRouter);

//  解决 Avoided redundant navigation to current location 报错问题
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};

const routes = [
  {
    path: '',
    name: 'dashboard',
    component: () => import('@/views/dashboard'),
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login'),
  },
  {
    path: '/account',
    name: 'account',
    component: { render: (h) => h('router-view') },
    children: [
      {
        path: 'list',
        name: 'account-list',
        component: () => import('@/views/account/list'),
      },
    ],
  },
  {
    path: '/user',
    name: 'user',
    component: { render: (h) => h('router-view') },
    children: [
      {
        path: 'list',
        name: 'user-list',
        component: () => import('@/views/user/list'),
      },
    ],
  },
  {
    path: '/works',
    name: 'works',
    component: { render: (h) => h('router-view') },
    children: [
      {
        path: 'list',
        name: 'works-list',
        component: () => import('@/views/works/list'),
      },
    ],
  },
  order,
  baseConfig,
  course,
];

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
});

router.beforeEach(async (to, from, next) => {
  if (to.path === '/login') {
    next();
  } else {
    const account = localStorage.getItem('account');
    if (account) {
      next();
    } else {
      next({ name: 'login' });
    }
  }
});
export default router;
